package com.lagou.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.lagou.bean.DeleteResult;
import com.lagou.bean.DownLoadResult;
import com.lagou.bean.UpLoadResult;
import com.lagou.config.AliyunConfig;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;
@Service
public class FileUpLoadService {
    @Autowired
    private AliyunConfig aliyunConfig;
    @Autowired
    private OSSClient  ossClient;
    // 允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{".jpg",
            ".jpeg", ".png"};//类型检查：必须为 jpg、png 或者 jpeg类型，其它图片类型返回错误提示信息
    public UpLoadResult  upload(MultipartFile multipartFile){
        // 校验图片格式
        boolean  isLegal = false;
        for (String type:IMAGE_TYPE){
            if(StringUtils.endsWithIgnoreCase(multipartFile.getOriginalFilename(),type)){
                isLegal = true;
                break;
            }
        }
        UpLoadResult upLoadResult = new UpLoadResult();

        if(multipartFile.getSize()>= 5*1024*1024){ //大小检查：必须小于5M，大于5M时返回错误提示信息
            upLoadResult.setStatus("error");
            upLoadResult.setResponse("文件大小不能超过5M！");
            return  upLoadResult;
        }
        if (!isLegal){
            upLoadResult.setStatus("error");
            upLoadResult.setResponse("文件格式不对！");
            return  upLoadResult;
        }
        String fileName = multipartFile.getOriginalFilename();
        String filePath = getFilePath(fileName);//图片名称：生成的文件名，必须保持唯一
        try {
            ossClient.putObject(aliyunConfig.getBucketName(),filePath,new ByteArrayInputStream(multipartFile.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            // 上传失败
            upLoadResult.setStatus("error");
            upLoadResult.setResponse("文件上传失败！");
            return  upLoadResult;
        }
        upLoadResult.setStatus("done");
        upLoadResult.setName(aliyunConfig.getUrlPrefix()+filePath);
        upLoadResult.setUid(filePath);
        return  upLoadResult;
    }

    public DownLoadResult download(String fileName) throws IOException {

//        String fileName = multipartFile.getOriginalFilename();
        String filePath = getFilePath(fileName);
        // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖，不存在则新建。
        OSSObject object = ossClient.getObject(new GetObjectRequest(aliyunConfig.getBucketName(), fileName));

        DownLoadResult downLoadResult=new DownLoadResult();
        if(object==null){
            downLoadResult.setStatus("erro");

            return downLoadResult;
        }
        downLoadResult.setStatus("ok");
        downLoadResult.setName(aliyunConfig.getUrlPrefix()+fileName);
        downLoadResult.setUid(filePath);
        return downLoadResult;
    }
    public DeleteResult delete(String fileName){
//        String fileName = multipartFile.getOriginalFilename();
        String filePath = getFilePath(fileName);

        DeleteResult deleteResult=new DeleteResult();
        // 删除文件。如需删除文件夹，请将ObjectName设置为对应的文件夹名称。如果文件夹非空，则需要将文件夹下的所有object删除后才能删除该文件夹。
       try {
           ossClient.deleteObject(aliyunConfig.getBucketName(), fileName);
       }catch (Exception e){
           e.printStackTrace();
           deleteResult.setStatus("erro");
           deleteResult.setResponse(e.toString());
           return deleteResult;
       }
        deleteResult.setStatus("ok");
        deleteResult.setName(aliyunConfig.getUrlPrefix()+fileName);
        deleteResult.setUid(filePath);
        return deleteResult;
    }

    // 生成不重复的文件路径和文件名
    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + UUID.randomUUID().toString() + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }
}
